package com.system.vote.admin.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.system.vote.common.utils.StringUtils;
import com.system.vote.core.customBean.PageBean;
import com.system.vote.core.customBean.RoleMenuBean;
import com.system.vote.core.customBean.UserRoleBean;
import com.system.vote.core.http.Result;
import com.system.vote.admin.entity.SysRole;
import com.system.vote.admin.entity.SysRoleMenu;
import com.system.vote.admin.entity.SysUserRole;
import com.system.vote.admin.service.SysRoleMenuService;
import com.system.vote.admin.service.SysRoleService;
import com.system.vote.admin.service.SysUserRoleService;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/sys/role")
@Api(tags = "PC后台用户角色")
public class SysRoleController {
    @Autowired
    SysRoleService sysRoleService;

    @Autowired
    SysUserRoleService sysUserRoleService;

    @Autowired
    SysRoleMenuService sysRoleMenuService;


    @GetMapping("/listAll")
    public Result gerRoleByUserId() {
        List<SysRole> roleList = sysRoleService.list();
        return Result.success(roleList);
    }

    @PostMapping("/save")
    @PreAuthorize("hasAuthority('system:role:add')" + "||" + "hasAuthority('system:role:edit')")
//    @AutoLog("新增或编辑用户角色")
    public Result saveUser(@RequestBody SysRole sysRole) {
        if (sysRole.getId() < 0) {
            Date d = new Date();
            sysRole.setCreateTime(d);
            sysRole.setUpdateTime(d);
            sysRoleService.save(sysRole);
        } else {
            sysRole.setUpdateTime(new Date());
            sysRoleService.updateById(sysRole);
        }
        return Result.success(sysRole);
    }

    @Transactional
    @PostMapping("/grantRole")
    @PreAuthorize("hasAuthority('system:user:role')")
//    @AutoLog("配置用户角色")
    public Result grantRole(@RequestBody UserRoleBean user) {

        System.out.println("HashMap:" + user.toString());
        Long userId = user.getUserId();
        Long[] roleArray = user.getRoleIds();

        sysUserRoleService.remove(new QueryWrapper<SysUserRole>().eq("user_id", userId));

        Collection<SysUserRole> roleList = new ArrayList<>();
        for (long o : roleArray) {
            SysUserRole sysUserRole = new SysUserRole();
            sysUserRole.setRoleId(o);
            sysUserRole.setUserId(userId);
            roleList.add(sysUserRole);
        }
        sysUserRoleService.saveBatch(roleList);
        return Result.success();
    }

    @PostMapping("/list")
    @PreAuthorize("hasAuthority('system:role:list')")
    public Result list(@RequestBody PageBean pageBean) {
        String query = pageBean.getQuery().trim();
        Page<SysRole> pageResult = sysRoleService.page(
                new Page<>(pageBean.getPageNum(),
                        pageBean.getPageSize()),
                new QueryWrapper<SysRole>().like(StringUtils.isNotEmpty(query), "name", query).orderByDesc("update_time"));
        List<SysRole> roleList = pageResult.getRecords();
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("roleList", roleList);
        resultMap.put("total", pageResult.getTotal());

        return Result.success(resultMap);
    }

    @GetMapping("/getMenuIds/{roleId}")
    @PreAuthorize("hasAuthority('system:role:menu')")
    public Result getMenuIds(@PathVariable Long roleId) {
        List<SysRoleMenu> menuIdList = sysRoleMenuService.list(new QueryWrapper<SysRoleMenu>().eq("role_id", roleId));
        return Result.success(menuIdList.stream().map(SysRoleMenu::getMenuId));
    }

    @Transactional
    @PostMapping("/setMenuIds")
    @PreAuthorize("hasAuthority('system:role:menu')")
//    @AutoLog("配置角色的菜单权限")
    public Result setMenuIds(@RequestBody RoleMenuBean menuParamObject) {
        Long[] menuIds = menuParamObject.getMenuIds();
        Long roleID = menuParamObject.getRoleId();
        sysRoleMenuService.remove(new QueryWrapper<SysRoleMenu>().eq("role_id", roleID));
        List<SysRoleMenu> menuList = new ArrayList<>();
        for (Long menuId : menuIds) {
            SysRoleMenu sysRoleMenu = new SysRoleMenu();
            sysRoleMenu.setMenuId(menuId);
            sysRoleMenu.setRoleId(roleID);
            menuList.add(sysRoleMenu);
        }
        sysRoleMenuService.saveBatch(menuList);
        return Result.success();
    }


    /**
     * 查看用角色列表
     *
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    @PreAuthorize("hasAuthority('system:role:query')")
//    @AutoLog("获得角色信息")
    public Result findById(@PathVariable(value = "id") Integer id) {
        SysRole sysRole = sysRoleService.getById(id);
        Map<String, Object> map = new HashMap<>();
        map.put("sysRole", sysRole);
        return Result.success(map);
    }

    /**
     * 查看角色名是否重名
     *
     * @param sysRole
     * @return
     */
    @PostMapping("/checkRoleName")
    @PreAuthorize("hasAuthority('system:role:query')")
    public Result checkRoleName(@RequestBody SysRole sysRole) {
        if (sysRoleService.getByRoleName(sysRole.getName()) == null) {
            return Result.success();
        } else {
            return Result.error();
        }
    }

    @PostMapping("/checkRoleCode")
    @PreAuthorize("hasAuthority('system:role:query')")
    public Result checkRoleCode(@RequestBody SysRole sysRole) {
        if (sysRoleService.getByRoleCode(sysRole.getCode()) == null) {
            return Result.success();
        } else {
            return Result.error();
        }
    }

    /**
     * @param ids
     * @return
     */
    @Transactional
    @PostMapping("/delete")
    @PreAuthorize("hasAuthority('system:role:delete')")
//    @AutoLog("删除角色")
    public Result delete(@RequestBody long[] ids) {
        List<Long> idList = Arrays.stream(ids).boxed().collect(Collectors.toList());
        //超级管理员不能删除
        if (idList.size() > 0) {
            //超级管理员不能删除
            idList.removeIf(n -> n == 1);
            sysRoleService.removeByIds(idList);
            //删除与角色相关的用户
            sysUserRoleService.remove(new QueryWrapper<SysUserRole>().in("role_id", idList));
            //删除与角色相关的菜单
            sysRoleMenuService.remove(new QueryWrapper<SysRoleMenu>().in("role_id", idList));
        }

        return Result.success();
    }

    public Result getMenuListByRoleId() {
        return Result.success();
    }
}


